package com.example.demo.client;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 *  模拟客户端访问测试
 *  使用httpClient访问
 */
public class ClientTest {
    public static void main(String[] args) {
        // 获取httpClient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建请求
        HttpGet httpGet = new HttpGet("http://localhost:8080/demo/services/rest/users/123");

        // 响应类型
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        try{
          response = httpClient.execute(httpGet);
          HttpEntity entity = response.getEntity();
          if (entity != null) {
              inputStream = entity.getContent();
              int len = 0; // 记录读取长度
              int tmp;
              byte[] data = new byte[1024]; // 开辟一个空间
              while ((tmp = inputStream.read()) != -1) {
                  data[len++] = (byte) tmp; // 保存在字节数组中
              }
              System.out.println("客户端访问到的内容: " + new String(data, 0, len));
          }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
